﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace Proyecto_Ajedrez.Objects
{
    class SQLInterface
    {
        public int validateUser(String user, String password)
        {
            int result = -1;
            SqlConnection connection = connect();

            if (connection != null)
            {
                try
                {
                    string query = "SELECT Nombre FROM Usuario " +
                                   "WHERE ID = '" + user +
                                   "' AND Password = '" + password + '\'';
                    SqlCommand command = new SqlCommand(query, connection);
                    SqlDataReader reader;
                    command.CommandType = CommandType.Text;
                    reader = command.ExecuteReader();

                    if (reader.HasRows)
                        result =  0;
                    else result = 1;
                }
                catch (Exception error)
                {
                    result = 2;
                }
            }
            else result = 3;

            disconnect(connection);
            return result;
        }

        private SqlConnection connect()
        {
            SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();
            scsb.DataSource = "tcp:mde.ccservices.biz";
            scsb.InitialCatalog = "Ajedrez";
            scsb.UserID = "ChessProject";
            scsb.Password = "Password123$";
            SqlConnection connection = new SqlConnection(scsb.ConnectionString);
            try
            {
                connection.Open();
            }
            catch (SqlException e)
            {
                Console.Write(e.Message);
            }
            return connection;
        }

        private void disconnect(SqlConnection connection)
        {
            try
            {
                connection.Close();
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
            }
        }
    }
}
